<template>
  <view>
    <view class="order-price-view">
      <view>
        <custom-price class="u-margin-top-30" :price="order.need_pay_price" :size="60" :fontWeight="400">
        </custom-price>
        <view>
          <text class="times-title">支付剩余时间</text>
          <u-count-down :timestamp="cancel_left_time" :show-days="false"></u-count-down>
        </view>
      </view>
    </view>

    <view class="payment-view u-margin-top-30">
      <view class="u-p-25">
        <u-checkbox
          v-model="isCheckPreDeposit"
          :disabled="!(account_balance > 0)"
          active-color="#ff5000"
          shape="square"
        >
          <view class="u-m-l-10 u-font-24">
            <text>
              使用预存款支付（预存款余额￥{{ account_balance | unitPrice }}，目前还需在线支付￥{{ order.need_pay_price | unitPrice }}）余额不足？
            </text>
            <text @click="handleRecharge">马上充值</text>
          </view>
        </u-checkbox>
        <view class="" v-if="isCheckPreDeposit">
          <u-message-input
            active-color="#ff5000"
            :maxlength="6"
            :dot-fill="true"
            @finish="handlePasswordFinish"
          ></u-message-input>
          <view class="tip-box">
            <view class="u-flex">
              <u-icon size="36" name="error-circle-fill"></u-icon>
              <text class="u-font-24 u-m-l-10">支付密码与用户登录密码不同，可在用户中心进行设置</text>
            </view>
            <navigator class="tip" url="/mine-module/account-safe" v-if="!order.deposite.is_pwd">您还未设置支付密码?
            </navigator>
            <navigator class="tip" url="/mine-module/account-safe" v-else>忘记密码?</navigator>
          </view>
        </view>
      </view>
    </view>

    <view class="payment-view u-margin-top-30">
      <view
        v-for="(pay, index) in paymentList"
        :key="index"
        class="u-flex u-row-between u-p-25"
        :class="index > 0 ? 'cell-view' : '' "
        @click="handlePaymentType(pay.plugin_id)"
      >
        <view class="cell-icon">
          <u-image width="200" height="60" :src="pay.image"></u-image>
        </view>
        <view class="cell-title">
          {{ pay.method_name }}
        </view>
        <view class="cell-right-icon">
          <u-icon :name="pay.selected ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
        </view>
      </view>
    </view>

    <view class="big-btn" @click="handlePayment" v-if="!isCheckPreDeposit">
      <view class="btn u-flex u-row-center">
        确认支付
        <custom-price :price="order.need_pay_price" :textColor="'#FFFFFF'"></custom-price>
      </view>
    </view>

    <!-- #ifdef H5 -->
    <div class="__pay_form__"></div>
    <!-- #endif -->
    <view v-if="debug">{{ log }}</view>
    <!-- 进入加载 -->
    <loading-view v-if="loading"></loading-view>
  </view>
</template>

<script>
import * as API_Trade from '@/api/trade'
import * as Payment from '@/common/payment'
import * as API_Deposit from '@/api/deposit'
import * as Openid from '@/api/openid'
import Cache, { Keys } from '@/utils/cache'
import { huiFuPay } from '@/config/config'

export default {
  data() {
    return {
      debug: false, //在app里显示调试日志
      openid: '',
      code: '',
      log: 'log',
      trade_sn: '',
      order_sn: '', //订单编号
      //订单详情
      order: {
        need_pay_price: '--'
      },
      is_callback: '', //是否是支付跳转回来的，如果为yes，表示是跳转回来的
      default_plugin_id: '', //默认要选中的支付方式
      paymentList: [], //支付方式列表
      payment_plugin_id: '', //支付方式
      cancel_left_time: '', //剩余支付时间
      account_balance: 0, //预存款余额
      isCheckPreDeposit: false, //是否使用预存款支付
      loading: true,
      noClick: true, //禁止多次点击
      queryPaymentStatusUrl: '',
      openHuiFuPay: huiFuPay
    }
  },
  onLoad(options) {
    this.trade_sn = options.trade_sn || ''
    this.order_sn = options.order_sn || ''
    this.is_callback = options.is_callback || ''
    this.default_plugin_id = options.default_plugin_id || ''
    this.openid = Cache.getItem(Keys.wxopenid)

    if (this.is_callback === 'yes') {
      this.payCallback()
    }

    // #ifdef APP-PLUS
    this.openid = 'appopenid'
    // #endif

    // #ifdef H5
    this.code = options.code || ''
    // #endif

    this.loadPaymentList()
    this.getCancelLeftTime()
  },
  onShow() {
    if (this.openHuiFuPay && this.queryPaymentStatusUrl) {
      this.queryPaymentStatus()
    }
  },
  watch: {
    isCheckPreDeposit(val) {
      if (!val) return
      this.paymentList.forEach(item => {
        item.selected = false
      })
    }
  },
  computed: {
    isWechat() {
      let isWechat = false
      // #ifdef H5
      isWechat = navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
      // #endif
      return isWechat
    }
  },
  methods: {
    // 获取订单取消剩余时间
    getCancelLeftTime() {
      const trade_type = this.trade_sn ? 'TRADE' : 'ORDER'
      const sn = this.trade_sn || this.order_sn
      API_Trade.getCancelLeftTime(trade_type, sn).then(response => {
        this.cancel_left_time = response
        this.loading = false
      })
    },
    //马上充值
    handleRecharge() {
      uni.navigateTo({
        url: "/mine-module/account-balance"
      })
    },
    //支付密码输入结束
    handlePasswordFinish(password) {
      const trade_type = this.trade_sn ? 'TRADE' : 'ORDER'
      const sn = this.trade_sn || this.order_sn
      const params = {
        sn,
        trade_type,
        password
      }
      API_Deposit.getBalancePay(trade_type, sn, params).then(response => {
        if (Number(response.need_pay) === 0) {
          uni.redirectTo({ url: '/order-module/payment-complete/payment-complete' })
        } else {
          this.isCheckPreDeposit = false
          this.password = ''
          this.loadPaymentList()
        }
      })
    },
    loadMiniOpenId() {
      if (!this.openid) {
        Openid.fetchWeixinMiniOpenId().then(openid => {
          this.openid = openid
          this.initiatePay()
        }).catch(e => {
          return this.$u.toast(`获取openid出现意外错误`)
        })
      } else {
        this.initiatePay()
      }
    },
    loadH5OpenId(code) {
      // 非微信内部，跳过获取openid
      if (!this.isWechat) {
        this.openid = 'h5openid'
      }
      if (!this.openid) {
        if (code === '') {
          Openid.createRedirectUri().then(url => {
            location.href = url
          })
        } else {
          Openid.fetchWeiXinH5OpenId(code).then(openid => {
            this.openid = openid
            this.initiatePay()
          }).catch(e => {
            return this.$u.toast(`获取openid出现意外错误`)
          })
        }
      } else {
        this.initiatePay()
      }
    },
    loadPaymentList() {
      let client_type = ''
      // #ifdef APP-PLUS
      client_type = 'NATIVE'
      // #endif
      // #ifdef H5
      client_type = 'WAP'
      // #endif
      // #ifdef MP
      client_type = 'MINI'
      // #endif
      Promise.all([
        this.trade_sn ?
          API_Trade.getCashierData({ trade_sn: this.trade_sn }) :
          API_Trade.getCashierData({ order_sn: this.order_sn }),
        API_Trade.getPaymentList(client_type),
        API_Deposit.getDepositBalance()
      ]).then(response => {
        this.order = response[0]
        this.account_balance = response[2]
        if (response[1] && response[1].length) {
          // 默认不选中支付方式
          response[1].forEach(item => {
            item.selected = false
            //如果传递了default_plugin_id则选中此支付方式
            if (item.plugin_id === this.default_plugin_id) {
              item.selected = true
            }
          })
          this.paymentList = response[1]

          // #ifdef H5
          if (!this.isWechat) {
            // 如果是H5并且不在微信浏览器内，隐藏微信支付
            this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'weixinPayPlugin')
          }
          // #endif

          // #ifndef MP-WEIXIN
          // 如果是在微信浏览器内则隐藏支付宝支付
          if (this.isWechat) {
            this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
          }
          // #endif

          // 如果是在小程序内则隐藏支付宝支付
          // #ifdef MP-WEIXIN
          this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
          // #endif
        }

        if (this.default_plugin_id == '') {
          this.paymentList[0].selected = true
          this.payment_plugin_id = this.paymentList[0].plugin_id
        } else {
          this.payment_plugin_id = this.default_plugin_id
        }

      })
    },
    //选择支付方式
    handlePaymentType(plugin_id) {
      this.paymentList.forEach(item => {
        item.selected = item.plugin_id === plugin_id
      })
      this.payment_plugin_id = plugin_id
    },
    payCallback() {
      uni.showModal({
        title: '支付提示',
        content: '请确认支付是否完成',
        confirmText: '支付成功',
        cancelText: '重新支付',
        success: (res) => {
          if (res.confirm) {
            uni.redirectTo({ url: '/order-module/order/order-list' })
          }
        }
      })
    },
    payFail(err) {
      if (this.debug) {
        this.log = 'fail:' + JSON.stringify(err)
      }
    },
    // 确定支付
    handlePayment() {
      // #ifdef H5
      if (this.payment_plugin_id === 'weixinPayPlugin') {
        this.loadH5OpenId(this.code)
      } else {
        this.initiatePay()
      }
      // await this.$u.throttle(this.loadH5OpenId(this.code), 2000)
      // #endif

      // #ifdef MP-WEIXIN
      this.$u.throttle(this.loadMiniOpenId(), 2000)
      // #endif

      // #ifdef APP-PLUS
      this.initiatePay()
      // #endif
    },
    async initiatePay() {
      if (!this.paymentList.some(item => item.selected)) {
        this.$u.toast(`请选择支付方式`)
        return
      }
      const trade_type = this.trade_sn ? 'trade' : 'order'
      const sn = this.trade_sn || this.order_sn
      const openid = this.openid
      let client_type
      // #ifdef APP-PLUS
      client_type = 'NATIVE'
      // #endif

      // #ifdef H5
      client_type = 'WAP'
      // #endif

      // #ifdef MP
      client_type = 'MINI'
      // #endif
      const pay_mode = 'normal'
      const payment_plugin_id = this.payment_plugin_id

      let uni_app = ''
      // #ifdef H5
      uni_app = 'H5'
      // #endif
      // #ifndef H5
      uni_app = 'UNH5'
      // #endif

      uni.showLoading({ title: '加载中...', mask: true })
      try {
        const response = await API_Trade.initiatePay(trade_type, sn, {
          client_type,
          pay_mode,
          uni_app,
          payment_plugin_id,
          openid
        })
        if (payment_plugin_id === 'weixinPayPlugin') {
          // 微信内嵌H5，调用wechatH5Pay方法
          // #ifdef H5
          if (typeof WeixinJSBridge == "undefined") {
            Payment.mobileH5Pay(response, this.payCallback, this.payFail)
          } else {
            if (this.openHuiFuPay) {
              const payInfo = JSON.parse(response.expend.pay_info)
              Payment.wechatH5Pay(payInfo, this.payCallback, this.payFail)
            } else {
              Payment.wechatH5Pay(response, this.payCallback, this.payFail)
            }
          }
          // #endif

          // 微信小程序，调用wechatMiniPay方法
          // #ifdef MP-WEIXIN
          if (this.openHuiFuPay) {
            const payInfo = JSON.parse(response.expend.pay_info)
            Payment.wechatMiniPay(payInfo, this.payCallback, this.payFail)
          } else {
            Payment.wechatMiniPay(response, this.payCallback, this.payFail)
          }
          // #endif

          //微信App
          // #ifdef APP-PLUS
          console.log('调用微信APP支付')
          Payment.wechatAppPay(response, this.payCallback, this.payFail)
          // #endif

          return
        }
        // #ifdef H5
        if (this.openHuiFuPay) {
          if (payment_plugin_id === 'unionYunPlugin') {
            // H5银联支付
            document.write(response.expend.form_html)
          } else if (payment_plugin_id === 'alipayDirectPlugin') {
            // 调起支付宝支付
            this.queryPaymentStatusUrl = response.query_url
            window.location.href = response.expend.pay_info
          }
        } else {
          // 调起支付宝支付
          Payment.aliPayH5(response, this.payCallback, this.payFail)
        }
        // #endif
        // #ifdef APP-PLUS
        Payment.aliPayApp(response, this.payCallback, this.payFail)
        // #endif
      } finally {
        uni.hideLoading()
      }
    },
    // 查询支付状态
    queryPaymentStatus() {
      uni.showLoading({ title: '请稍候', mask: true })
      uni.request({
        url: this.queryPaymentStatusUrl,
        success: (result) => {
          const { status } = result.data
          if (status === 'successed') {
            uni.showModal({
              title: '提示',
              content: '支付成功！',
              showCancel: false,
              confirmText: '查看订单列表',
              success: () => {
                uni.redirectTo({ url: '/order-module/order/order-list' })
              }
            })
          } else if (status === 'failed') {
            uni.showModal({
              title: '提示',
              content: '支付失败！',
              showCancel: false,
              confirmText: '重新支付'
            })
          } else {
            uni.showModal({
              title: '提示',
              content: '支付成功了吗？',
              cancelText: '重新支付',
              confirmText: '查看订单列表',
              success: (result) => {
                if (result.confirm) {
                  uni.redirectTo({ url: '/order-module/order/order-list' })
                }
              }
            })
          }
        },
        complete: () => {
          uni.hideLoading()
        }
      })
    }
  }
}
</script>

<style lang="scss">
.order-price-view {
  background-color: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 50rpx;
  text-align: center;
  .order-price {
    font-size: 45rpx;
    color: #ff5000;
    font-weight: bold;
  }
  .times-title {
    margin: 0 10rpx;
  }
}
.payment-view {
  margin: 20rpx;
  border-radius: 20rpx;
  background-color: #FFFFFF;
  .cell-view {
    border-top: 2rpx solid #E5E5E5;
  }
  .cell-icon {
    padding: 10rpx 0rpx;
  }
  .cell-title {
    text-align: right;
    flex: 1;
    margin: 0 20rpx;
    font-size: 30rpx;
    font-weight: bold;
  }
}
.tip-box {
  padding-left: 20rpx;
  margin-top: 20rpx;
  color: #ffcc00;
  .tip {
    display: inline-block;
    background-color: #F59C1A;
    border-color: #F59C1A;
    color: #FFF;
    padding: 8rpx 16rpx;
    border-radius: 10rpx;
    margin: 20rpx 0 0 10rpx;
    font-size: 24rpx;
  }
}
/deep/ {
  .custom-icon-xuanze {
    color: #ff5000;
    font-size: 40rpx !important;
  }
  .custom-icon-choose {
    font-size: 40rpx !important;
  }
}
</style>
